package com.iweibo.logic;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

import com.iweibo.bean.Task;
import com.iweibo.interfaces.IWeiboActivity;

import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

public class MainService extends Service implements Runnable {

	private static final String TAG = "MainService";
	// 任务队列
	private static Queue<Task> tasks = new LinkedList<Task>();
	private static ArrayList<Activity> appActivities = new ArrayList<Activity>(5);
	
	// 是否运行线程,false=不运行;true=运行
	private boolean isRun = false;
	
	public static void addTask(Task task) {
		tasks.add(task);
	}
	
	@Override
	public void run() {
		Task task = null;
		while (isRun) {
			if (!tasks.isEmpty()) {
				task = tasks.poll();
				doTask(task);
			}
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				Log.e(TAG, "MainService run error!", e);
			}
		}
	}
	
	
	private void doTask(Task task) {
		Message msg = handler.obtainMessage();
		msg.what = task.getTaskId();
		
		switch (task.getTaskId()) {
		case Task.WEIBO_LOGIN:
			Log.i(TAG, "微博登陆!");
			msg.obj = "登陆成功!";
			break;

		default:
			break;
		}
		handler.sendMessage(msg);
	}
	
	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Task.WEIBO_LOGIN:
				IWeiboActivity activity = (IWeiboActivity)getActivityByName("LoginActivity");
				activity.refresh(msg.obj);
				break;
			default:
				break;
			}
		}
	};
	
	private Activity getActivityByName(String name) {
		if (!appActivities.isEmpty()) {
			for (Activity activity : appActivities) {
				if (null != activity && activity.getClass().getName().indexOf(name) > 0) {
					return activity;
				}
			}
		}
		return null;
	}
	
	public static void addActivity(Activity activity) {
		appActivities.add(activity);
	}

	@Override
	public void onCreate() {
		isRun = true;
		Thread thread = new Thread(this);
		thread.start();
		super.onCreate();
	}


	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

}
